import './../sass/header.scss';
import './../font/iconfont.css';
import './../sass/index.scss';
import { getinfo } from './../js/auth.js';

const $ = require('jquery');

const token = localStorage.token;


// 图片上传
$("#icon").on('change', function (e) {
    const files = e.target.files;
    const fd = new FormData();
    fd.append("file", files[0]);
    $.ajax({
        url: '/images/uploadImages',
        data: fd,
        type: 'post',
        success({ message, path }) {
            $("#icon").attr("data-src", path);
            $("#imgshow").prop("src", path);
        },
        contentType: false,
        processData: false,
        cache: false,
    })
})

// 关闭模块
$("#cancel").on('click', function () {
    $("#user_model").fadeOut();
})

// 修改数据
$("#save").on('click', function () {
    let gender = $("#gender input:checked").val();
    switch (gender) {
        case '0':
            gender = '男'
            break;
        case '1':
            gender = '女'
            break;
        default:
            break;
    }
    $.ajax({
        url: '/students/changeStudent',
        data: {
            phone: $("#userPhone").text(),
            name: $("#uname").val(),
            gender: gender,
            avatar: $("#icon").attr("data-src")
        },
        type: 'post',
        success({ message, code, token, data }) {
            $("#user_model").fadeOut();
            getinfo();
            $("#icon").val('');
            $("#uname").val('');
        }
    })
})

// 切换账号
$("#change_acount").on('click', function () {
    localStorage.removeItem('token');
    location.assign('./../html/login.html');
})
// 退出登录
$("#sign_out").on('click', function () {
    localStorage.removeItem('token');
    location.assign('./../html/login.html');
})



// 五大模块
$.ajax({
    url: '/types',
    success(data) {
        $("#test_model").html(
            `<li data-id="${data[1]._id}"><span>${data[1].type}</span><i class="iconfont icon-jinru"></i></li>
            <li data-id="${data[2]._id}"><span>${data[2].type}</span><i class="iconfont icon-xitongtuisong"></i></li>
            <li data-id="${data[0]._id}"><span>${data[0].type}</span><i class="iconfont icon-yanchurili"></i></li>
            <li data-id="${data[3]._id}"><span>${data[3].type}</span><i class="iconfont icon-caozuo-xunhuan1"></i></li>
            <li data-id="${data[4]._id}"><span>${data[4].type}</span><i class="iconfont icon-caidan"></i></li>`
        )
    }
})
// 五大模块点击事件
$("#test_model").on('click', 'li', function () {
    location.assign(`./../html/questionbank.html?title=${$(this).text()}`);
})

// rank
$("#rank").on('click', function () {
    $.ajax({
        url: '/testeds/getTested',
        type: 'post',
        success({ message, code, result }) {
            $("#rank_content").html('');
            const rank = result.sort((a, b) => b.score - a.score);
            const rankList = rank.map((item, index) =>
                `<li><i>第${index + 1}名</i><div>${item.studentId.name}</div><div>总分：${item.score}分</div></li>`
            )
            $("#rank_content").html(rankList);
        }
    })
    $("#rank_model").show()
})
$("#rank_model").on('click', function () {
    $("#rank_model").hide()
})

// 学习天数
function sign() {
    let days = 0;
    const signs = $("#sign li");
    [...signs].forEach(item => {
        if ($(item).attr("class") == "isSign") {
            days++;
        }
    })
    $("#testdays").text(days);
}
sign()

// 签到
const signs = $("#sign li");
[...signs].forEach(item => {
    $(item).on('click',function() {
        if ($(item).attr("class") == "isSign") {
            $(item).removeClass("isSign")
        }else{
            $(item).addClass("isSign")
        }
        sign()
    })
})


$("#set_btn").on('click', function () {
    $("#seting").slideToggle();
})

// 个人资料
$("#user").on('click', function () {
    $("#user_model").fadeIn();
})
$("#close").on('click', function () {
    $("#user_model").fadeOut();
})



// 导航切换效果
const navs = $("#nav li");
const sections = $("#content > section");
[...navs].forEach((item, index) => {
    $(item).on('click', function () {
        switch (index) {
            case 0:
                $("#backGeound").css('width', '152px');
                $("#backGeound").css('left', '0');
                break;
            case 1:
                $("#backGeound").css('width', '220px');
                $("#backGeound").css('left', '152px');
                break;
            case 2:
                $("#backGeound").css('width', '200px');
                $("#backGeound").css('left', '372px');
                break;

            default:
                break;
        }
        $(item).siblings().removeClass('active');
        $(item).addClass('active');
        sections.eq(index).siblings().hide();
        sections.eq(index).show();
    })
});



/**
 * 公告模块
 */

// 数据看板
// 练习题数
$.ajax({
    url: '/testeds/getTested',
    type: 'post',
    success({ result }) {
        $.ajax({
            url: '/auth/token',
            type: 'post',
            success({ user }) {
                const tests = result.filter(item => {
                    item.studentId._id == user.user._id
                });
                if (tests != 0) {
                    $("#testnum").text(tests.length);
                    $("#testscore").text(tests[0].score);
                } else {
                    $("#testnum").text(0);
                    $("#testscore").text(0);
                }
            }
        })
    }
})


// 公告效果
$("#notice").on('click', 'li', function () {
    $("#notice_model").fadeIn();
    $(this).addClass('readed')
    $(this).find('i').css('display', 'none');
})

$("#notice_close").on('click', function () {
    $("#notice_model").fadeOut();
})

$("#selscted").on('change', function () {
    switch ($(this).val()) {
        case 'total':
            $("#notice li").show();
            break;
        case 'read':
            $("#notice li").hide();
            $("#notice .read").show();
            break;
        case 'unread':
            $("#notice li").show();
            $("#notice .read").hide();
            break;

        default:
            break;
    }
})

// 更多
$("#more").on('click', function () {
    $("#notice").css('height', `${Number($("#notice").css('height').replace('px', '')) + 200}px`)
})



/**
 * 收藏模块
 */

// 获取我的收藏数据及渲染
function collectionRender() {
    $.ajax({
        url: '/auth/token',
        type: 'post',
        success({ message, code, user }) {
            $.ajax({
                url: `/collections/getCollections/${user.user._id}`,
                success({ message, code, result }) {
                    if (code == '1') {
                        $("#myCollections").text(`我的收藏(${result.length})`)
                        $("#Collections").html('');
                        const tests = result.map((item, index) =>
                            `<li>
                                <p>${item.exerciseId.topics}</p>
                                <ul>
                                    <li>
                                        <i>A</i>
                                        ${item.exerciseId.options[0]}
                                    </li>
                                    <li>
                                        <i>B</i>
                                        ${item.exerciseId.options[1]}
                                    </li>
                                    <li>
                                        <i>C</i>
                                        ${item.exerciseId.options[2]}
                                    </li>
                                    <li>
                                        <i>D</i>
                                        ${item.exerciseId.options[3]}
                                    </li>
                                </ul>
                                <section>
                                    <button id="cancel_collection" data-collectionId="${item._id}">取消收藏</button>
                                    <div>
                                        <button class="prev">上一题</button>
                                        <button class="next">下一题</button>
                                    </div>
                                </section>
                                <aside class="collection_resolution">
                                    <p>考生答案: <span>B</span></p>
                                    <p>正确答案: <span>${answer(item.exerciseId.answer)}</span></p>
                                    <p>${item.exerciseId.analysis}</p>
                                </aside>
                            </li>`
                        )
                        $("#Collections").html(tests);

                        // 答题卡渲染
                        $("#collectionAnswerSheet").html('');
                        const sheets = result.map((item, index) => [
                            `<div>${index + 1}</div>`
                        ])
                        $("#collectionAnswerSheet").html(sheets);

                        sheet($("#collectionAnswerSheet div"), "#Collections");
                    }
                }
            })
        }
    })
}
collectionRender();

// 取消收藏功能
$("#Collections").on('click', '#cancel_collection', function () {
    $.ajax({
        url: '/collections/deleteCollections',
        data: {
            id: $(this).attr("data-collectionId")
        },
        type: 'post',
        success({ message, code }) {
            msg(message);
        }
    })
})


// 答题卡点击事件
function sheet(sheets, target) {
    [...sheets].forEach((item, index) => {
        $(item).on('click', function () {
            $(target).css('left', `-${index * 500}px`)
        })
    })
}

// 收藏解析切换
$("#collection_switch").on('click', function () {
    $(".collection_resolution").fadeToggle();
})



// 收藏试题切换
$("#collection_subject").on('click', 'button', function () {
    const topicposition = Number($(this).parents('ul').css('left').replace('px', ''));
    switch ($(this).text()) {
        case '上一题':
            if (topicposition != 0) {
                var topicLeft = topicposition + 500;
                $("#collection_subject .wrape").css('left', `${topicLeft}px`);
            }
            break;
        case '下一题':
            if (topicposition != -($("#Collections > li").length - 1) * 500) {
                var topicLeft = topicposition - 500;
                $("#collection_subject .wrape").css('left', `${topicLeft}px`);
            }
            break;
    }
})

/**
 * 错题库模块
 */

// 获取错题库数据及渲染
function errorRender() {
    $.ajax({
        url: '/auth/token',
        type: 'post',
        success({ message, code, user }) {
            $.ajax({
                url: `/errors/getErrors/${user.user._id}`,
                success({ message, code, result }) {
                    if (code == '1') {
                        $("#myErrors").text(`错题库(${result.length})`)
                        $("#Errors").html('');
                        const tests = result.map((item, index) =>
                            `<li>
                                <p data-errorExerciseId="${item.exerciseId._id}">${item.exerciseId.topics}</p>
                                <ul>
                                    <li>
                                        <i>A</i>
                                        ${item.exerciseId.options[0]}
                                    </li>
                                    <li>
                                        <i>B</i>
                                        ${item.exerciseId.options[1]}
                                    </li>
                                    <li>
                                        <i>C</i>
                                        ${item.exerciseId.options[2]}
                                    </li>
                                    <li>
                                        <i>D</i>
                                        ${item.exerciseId.options[3]}
                                    </li>
                                </ul>
                                <section>
                                    <button id="collection_btn">收藏</button>
                                    <button id="del_btn" data-errorId="${item._id}">标记已学会</button>
                                    <div>
                                        <button class="prev">上一题</button>
                                        <button class="next">下一题</button>
                                    </div>
                                </section>
                                <aside class="error_resolution">
                                    <p>考生答案: <span>B</span></p>
                                    <p>正确答案: <span>${answer(item.exerciseId.answer)}</span></p>
                                    <p>${item.exerciseId.analysis}</p>
                                    <div class="errorSign">错误</div>
                                </aside>
                            </li>`
                        )
                        $("#Errors").html(tests);

                        // 答题卡渲染
                        $("#errorAnswerSheet").html('');
                        const sheets = result.map((item, index) => [
                            `<div>${index + 1}<i class="iconfont icon-cuowu"></i></div>`
                        ])
                        $("#errorAnswerSheet").html(sheets);

                        sheet($("#errorAnswerSheet div"), "#Errors");
                    }
                }
            })
        }
    })
}
errorRender();

// 添加收藏功能
$("#Errors").on('click', '#collection_btn', function () {
    $.ajax({
        url: '/collections/createCollections',
        type: 'post',
        data: {
            exerciseId: $(this).parents('li').find("p").attr("data-errorExerciseId"),
            studentId: $("#user").attr("data-studentid")
        },
        success({ message, code }) {
            msg(message);
        }
    })
})

// 标记已学会
$("#Errors").on('click', '#del_btn', function () {
    $.ajax({
        url: '/errors/deleteErrors',
        type: 'post',
        data: {
            id: $(this).attr("data-errorId")
        },
        success({ message, code }) {
            msg(message);
        }
    })
})

// 错误解析切换
$("#error_switch").on('click', function () {
    $(".error_resolution").fadeToggle();
})

// 错误试题切换
$("#error_subject").on('click', 'button', function () {
    const topicposition = Number($(this).parents('ul').css('left').replace('px', ''));
    switch ($(this).text()) {
        case '上一题':
            if (topicposition != 0) {
                var topicLeft = topicposition + 500;
                $("#error_subject .wrape").css('left', `${topicLeft}px`);
            }
            break;
        case '下一题':
            if (topicposition != -($("#Errors > li").length - 1) * 500) {
                var topicLeft = topicposition - 500;
                $("#error_subject .wrape").css('left', `${topicLeft}px`);
            }
            break;
    }
})


// 答案转换
function answer(answer) {
    switch (answer) {
        case '0':
            return 'A';
        case '1':
            return 'B';
        case '2':
            return 'C';
        case '3':
            return 'D';

        default:
            break;
    }
}

// 消息弹窗
function msg(content) {
    $("#msg").text(content);
    $("#msg").fadeIn();
    const timer = setTimeout(() => {
        $("#msg").fadeOut();
        clearTimeout(timer);
    }, 1000);
}